/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fait.ferm.persists;

import fait.ferm.global.Glob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Date;

/**
 *
 * @author Greg
 */
public class Plan extends PersistsObject {
    public Ferm ferm;
    public Date date_beg;
    public Date date_end;
    public Date realized;
    
    public Plan() {
        super();
        ferm = Glob.getFerm();
        date_beg = null;
        date_end = null;
        realized = null;
        
        table = "plan";
    }
    
    public Plan(int pId) throws Exception {
        super(pId);
        ferm = Glob.getFerm();
        table = "plan";
        load();
    }
    
    @Override
    public void load() throws Exception {
        boolean notSuccessfully=true;
		if(id==-1) {
			throw new Exception("Объект "+table+" отсутствует в базе");
		}	
		try (Statement st = con.createStatement()) {
			String q = "SELECT ferm_id, date_beg, date_end, realized FROM "+table+" WHERE id = " + id;
			ResultSet rs = st.executeQuery(q);
			if(rs.next()){
                notSuccessfully=false;
                if(rs.getInt("ferm_id") != ferm.getId()) {
                    throw new Exception("Объект "+table+" не из этой игры");
                }
                date_beg = Date.valueOf(rs.getString("date_beg"));
				date_end = Date.valueOf(rs.getString("date_end"));
                try {
                    realized = Date.valueOf(rs.getString("realized"));
                } catch(Exception ex) {
                    realized = null;
                }
			}
			rs.close();
		}
		if(notSuccessfully) {
			throw new Exception("Объект "+table+" не загружен");
        }
    }

    @Override
    protected void update() throws SQLException {
        try (Statement st = con.createStatement()) {
			String q = "UPDATE "+table+" SET date_beg='"+date_beg.toString()+"', date_end='"+date_end+
					"', realized = '"+ realized + "' " +
					"WHERE id="+id;
			st.executeUpdate(q);
		}
    }

    @Override
    protected void createNew() throws SQLException, Exception {
        try (Statement st = con.createStatement()) {
			String q = "INSERT INTO "+table+" (ferm_id, date_beg, date_end, realized) VALUES("+ferm.getId() + ",'" + date_beg.toString() + "','"
					+date_end.toString()+"','"+realized+"') ";
			st.executeUpdate(q);
			q="SELECT seq FROM sqlite_sequence WHERE name = '"+table+"'";
			ResultSet rs = st.executeQuery(q);
			if(rs.next()){
				id = rs.getInt("seq");
			}
			rs.close();
		}
    }
    
}
